package com.fingard.dsp.bank.directbank.xib01;

import com.alibaba.fastjson.JSONObject;
import com.fingard.io.FileHelper;
import org.apache.axis.utils.StringUtils;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;

import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Date;

/**
 * Created by F on 2017/7/10.
 */
public class XIB01Base extends DirectBase {
    /// <summary>
    /// 公共头部
    /// </summary>
    /// <param name="接口编码"></param>
    /// <returns></returns>
    public String writeHeader(String txnCode) throws Exception {
        StringBuilder writer = new StringBuilder();

        //String postJSON = "{\"RequestData\":\"" + toSignStr + "\",\"Sign\":\"" + signnature + "\"}";
        //银企客户编号
        writer.append("{\"custId\":\"" + bankFront.loginName + "\",");
        //接口版本
        writer.append("\"version\":\"1.0\",");
        //请求时间
        writer.append("\"reqTime\":\"" + Format.Date8Format.format(new Date()) + "\",");
        //接口编码
        writer.append("\"txnCode\":\"" + txnCode + "\",");
        //语言编码
        writer.append("\"local\":\"zh_CN\",");
        //请求流水号
        writer.append("\"extRefId\":\"" + reqHeader.transSeqID + "\",");
        //body
        writer.append("\"body\":");

        return writer.toString();
    }

    /**
     * 获取交互字符集
     *
     * @return
     */
    protected String getCharset(){
        return getBankConfig().getCharset("UTF-8");
    }

    protected String getQryTransID() {
        return Format.DateTime17Format.format(new Date());
    }

    /**
     * 公共请求
     * @param jsonObject
     * @param tmpBankHeader
     * @throws Exception
     */
    protected String writeCommonHead(JSONObject jsonObject, XIB01Header tmpBankHeader){
        JSONObject jsonHeader=new JSONObject();
        jsonHeader.put("custId",bankFront.loginName);
        jsonHeader.put("version","1.0");
        jsonHeader.put("reqTime",Format.Date8Format.format(new Date()));
        jsonHeader.put("txnCode",tmpBankHeader.txnCode);
        jsonHeader.put("local","zh_CN");
        jsonHeader.put("extRefId",tmpBankHeader.extRefId);
        jsonHeader.put("body",jsonObject);
        return jsonHeader.toJSONString();
    }

    /**
     * 请求到银行
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr=new String[]{"",""};
        WriteBankLogStep2(p_reqStr);
        String url = "http://" + bankFront.serverIP + ":" + bankFront.serverPort + "/ifspesi/dbe/api";
        WriteBankLogLn("发送银行地址" + url);
        WebRequest req = new WebRequest(url);
        req.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        byte[] data = p_reqStr.getBytes(getCharset());
        retStr = req.upload(data, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    /**
     * 从银行下载文件
     * @param downloadUrl 银行下载地址
     * @param localSavePath 本地保存路径
     * @return
     * @throws Exception
     */
    protected boolean sendToBankDownload(String downloadUrl,String localSavePath){
        WriteBankLogLn("请求下载地址："+downloadUrl);
        WriteBankLogLn("本地保存地址："+localSavePath);
        WebRequest webRequest=new WebRequest(downloadUrl);
        webRequest.download(localSavePath);
        if(FileHelper.existFile(localSavePath)){
            return true;
        }else {
            return false;
        }
    }

    public String postData(String str, String ip, String port) throws Exception {
        String url = "http://" + ip + ":" + port + "/ifspesi/dbe/api";

        WriteBankLogLn("发送银行地址" + url + "：\r\n" + str);

        byte[] data = str.getBytes("UTF8");
        //   准备请求
        WebRequest req = new WebRequest(url);
        req.setRequestProperty("Method", "POST");
        req.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        req.setRequestProperty("ContentLength", Integer.toString(data.length));
        //   发送数据
        String[] webRet = req.upload(data, "UTF-8");

        if (!StringUtils.isEmpty(webRet[0])) {
            throw new Exception(webRet[0]);
        }

        WriteBankLogLn(MessageFormat.format("银行返回原文：{0}\r\n\r\n", webRet[1]));
        return webRet[1];

    }

    protected String Signatures(String sign) throws Exception {
        WriteBankLogLn(String.format("发送签名端口报文：%s\r\n\r\n", sign));
        byte[] tmpToWriteBytes = sign.getBytes(Charset.forName("GBK"));
        long tmpBodyLength = tmpToWriteBytes.length;
        String _RemoteIP = bankFront.signURL;
        String _SecuPort = bankFront.signPort;


        WebRequest hwr = new WebRequest("http://" + _RemoteIP + ":" + _SecuPort);
        hwr.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
        hwr.setRequestProperty("ContentLength", Long.toString(tmpBodyLength));
        hwr.setRequestProperty("Accept-Language", "zh-cn");
        hwr.setRequestProperty("Pragma", "no-cache");
        hwr.setRequestProperty("Proxy-Connection", "Keep-Alive");
        hwr.setRequestProperty("Method", "POST");

        WriteBankLogLn("签名端口url：\"http://" + _RemoteIP + ":" + _SecuPort + "\r\n\r\n");

        String[] str_tmpBKRet = hwr.upload(tmpToWriteBytes, "GBK");
        if (!StringUtils.isEmpty(str_tmpBKRet[0])) {
            throw new Exception(str_tmpBKRet[0]);
        }

        WriteBankLogLn(MessageFormat.format("签名端口返回密文：{0}\r\n\r\n", str_tmpBKRet[1]));

        XmlTextReader xd_tmpDocment = new XmlTextReader(str_tmpBKRet[1]);
        int result = Integer.parseInt(GetDocNodeValue(xd_tmpDocment, "/html/head/result"));

        if (result == 0) {
            str_tmpBKRet[1] = str_tmpBKRet[1].replace("\n", "");
            str_tmpBKRet[1] = GetDocNodeValue(xd_tmpDocment, "/html/body/sign");
        }

        return str_tmpBKRet[1];
    }

    private String GetDocNodeValue(XmlTextReader p_SourceDoc, String p_NodeName) throws Exception {
        if (p_SourceDoc == null) return "";

        p_SourceDoc.read(p_NodeName);
        XElement xln_tmpPNode = p_SourceDoc.readedXElement;
        if (xln_tmpPNode == null)
            return "";
        else
            return xln_tmpPNode.innerText;
    }

    protected boolean IsResultValid(String retCode, String retMsg) {
        if (org.apache.commons.lang.StringUtils.equals(retCode, "-999") ||
                org.apache.commons.lang.StringUtils.equals(retMsg, "-999") ||
                !org.apache.commons.lang.StringUtils.equals(retCode, "00000")) {
            return false;
        }
        return true;
    }
}
